from fastapi import FastAPI
import anyio
import time

app = FastAPI()

def sync_function():
    time.sleep(5)  # 模拟一个耗时的同步操作
    return "Done"

@app.get("/")
async def root():
    result = await anyio.to_thread.run_sync(sync_function)  # 在线程池中运行
    return {"result": result}



from fastapi import FastAPI
import asyncio

app = FastAPI()

async def async_function():
    await asyncio.sleep(5)  # 异步等待
    return "Done"

@app.get("/")
async def root():
    result = await async_function()  # 直接调用异步函数
    return {"result": result}



from fastapi import FastAPI
from fastapi.concurrency import run_in_processpool
import time

app = FastAPI()

def cpu_intensive_function():
    # 模拟一个 CPU 密集型的操作
    result = sum(i * i for i in range(10**6))
    return result

@app.get("/")
async def root():
    result = await run_in_processpool(cpu_intensive_function)  # 在进程池中运行
    return {"result": result}


from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
import time

app = FastAPI()

def sync_function():
    time.sleep(5)  # 模拟一个耗时的同步操作
    return "Done"

@app.get("/")
async def root():
    result = await run_in_threadpool(sync_function)  # 在线程池中运行
    return {"result": result}            